package org.dalmatian.common.web.filter;

import org.dalmatian.common.core.exception.ServiceException;
import org.dalmatian.common.core.exception.base.BaseException;
import org.dalmatian.common.core.utils.MessageUtils;
import org.dalmatian.common.web.exception.CustomException;
import org.dalmatian.common.core.domain.R;
import org.noear.solon.annotation.Component;
import org.noear.solon.core.exception.StatusException;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Filter;
import org.noear.solon.core.handle.FilterChain;

/**
 * @author 张超
 * 统一异常处理
 */
@Component(index = 0)
public class GlobalExceptionHandlerFilter implements Filter
{
    @Override
    public void doFilter(Context ctx, FilterChain chain) throws Throwable {
        try {
            chain.doFilter(ctx);
        } catch (CustomException e){
            ctx.render(R.fail(e.getCode(), e.getMessage()));
        }
        catch (ServiceException e) {
            ctx.render(R.fail(e.getCode(), e.getMessage()));
        }
        catch (StatusException e){
            ctx.render(R.fail(e.getCode(), "请求路径不存在!"));
        }
        catch (BaseException e){
            ctx.render(R.fail(e.getCode(), MessageUtils.message(e.getCode(),e.getArgs())));
        }
        // todo 添加
        catch (Throwable e) {
            e.printStackTrace();
            ctx.render(R.fail(500,"内部服务器错误!"));
        }
    }
} 